package com.zjbd.douyangsystem.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zjbd.douyangcommoncore.entity.DyNews;
import com.zjbd.douyangcommoncore.result.Result;
import com.zjbd.douyangcommoncore.service.DyNewsService;
import com.zjbd.douyangcommoncore.utils.RocketMQUtil;
import com.zjbd.douyangcommoncore.vo.DyNewsVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Tag(name = "新闻相关")
@RestController
@RequestMapping("/douyang/system/news")
public class NewsController {

    @Autowired
    private DyNewsService dyNewsService;

    @Resource
    private RocketMQUtil rocketMQUtil;

    //添加新闻
    @SentinelResource(
            value = "addNews", // 资源名称
            blockHandlerClass = NewsController.class, // 完整类名（若在同一包下可省略包名）
            blockHandler = "blockHandlerMethod" //限流执行的方法
    )
    @Operation(summary = "添加新闻")
    @PostMapping("/addNews")
    public Result addNews(@RequestBody DyNewsVo dyNewsVo){
        log.info("添加新闻：{}",dyNewsVo);
        DyNews dyNews = new DyNews();
        //Vo转换成Entity
        BeanUtil.copyProperties(dyNewsVo,dyNews);
        dyNewsService.save(dyNews);

        //同步把添加新闻的这个事情给MQ
        RocketMQUtil.SendResultVO result = rocketMQUtil.broadcastSend("news-add-topic", dyNews);
        if (result.isSuccess()) {
            log.info("广播消息发送成功 | msgId: {}", result.getMsgId());
        } else {
            log.error("广播消息发送失败 | 原因: {}", result.getErrMsg());
        }

        return Result.success("添加成功");
    }

    // 触发限流执行的方法
    // BlockException 是限流异常
    public static Result blockHandlerMethod(DyNewsVo dyNewsVo, BlockException e){
        return Result.error("当前服务压力大，请稍后重试。（触发限流了）");
    }





}
